// 页面基类
module.exports = Behavior({
  properties: {},
  data: {
    /**
     * 检查用户手机号
     */
    checkMobile: true,
    host: 'https://yjk.lphp.site/',
    imgHost: 'https://yjk.lphp.site',
    userInfo: { //用户数据
      uid: '',
      /**0:待审核,1:通过认证,2:认证被拒绝,3未提交 */
      supplier_verify: 3,
      nickname: '',
      face: '',
      /**积分 */
      points: 0,
    },
    contact: {
      tel: '400-'
    }, //联系客服电话，微信，坐标 
  },
  created: function () {},
  attached: function () {},
  ready: function () {

    this.data.userInfo = getApp().globalData.userInfo;
    console.log('基类 ready', this.data.userInfo);

  },

  methods: {
    onLoad: function (options) {
      console.log('基类 onload');
      this.data.userInfo = getApp().globalData.userInfo;
    },
    
    /**登陆状态更新之后重载的方法 */
    login_reload() {
      console.log("执行基类重载方法")
      this.data.userInfo = getApp().globalData.userInfo;
    },
    /**拨打客服电话 */
    call_phone(e) {
      // e.currentTarget
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel || getApp().globalData.config1.mobile
      })
    },
    /**隐藏弹窗通用方法 */
    hide_popup(e) {
      // console.log("hide_popup", e)
      let obj = {};
      obj[e.currentTarget.dataset.field] = false;
      this.setData(obj)
    },
    /**显示弹窗通用方法 */
    show_popup(e) {
      // console.log("hide_popup", e)
      let obj = {};
      obj[e.currentTarget.dataset.field] = true;
      this.setData(obj)
    },
    /**
     * 获取完整的缩略图地址
     * @param {string} url 
     * @param {string} type  缩略图大小，默认small,中图wide
     */
    get_thumb(url, type = 'small') {
      let thumb = '/assets/common/logo.png';
      if (url) {
        thumb = this.data.imgHost + '/' + url + '!' + type;
      }
      return thumb
    },

    // 微信登陆
    getUserInfo() {
      let that = this;
      // return;
      wx.login({
        withCredentials: true,
        timeout: 10000,
        success(res) {
          if (res.code) {
            let code = res.code;
            that.request({
              method: 'GET',
              url: that.data.host + '/home/login',
              data: {
                code: code,
              }
            }, res => {
              // wx.showToast({
              //   title: '登陆成功',
              // })
              wx.setStorageSync('Authorization', res.data.access_token)
              that.data.userInfo = getApp().globalData.userInfo = res.data;
              console.log("登陆成功，检测用户资料状态");
              that.check_mobile();
              that.login_reload()
            });


          } else {
            wx.showToast({
              icon: 'none',
              title: '登录失败！' + res.errMsg,
            })
          }
        },
        fail(res) {

          wx.showToast({
            icon: 'none',
            title: res.errMsg || '获取微信授权失败',
          })
        }
      })
    },
    /**
     * 获取用户信息(头像，昵称等)
     */
    getUserProfile() {
      console.log("getUserProfile");
      let that = this;
      let userInfo = this.data.userInfo;
      wx.showModal({
        content: '请授权完善头像，昵称等信息',
        showCancel: true,
        title: '完善信息',
        success: (result) => {
          if (result.confirm) {
            wx.getUserProfile({
              desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
              success: (user) => {
                that.request({
                  url: that.data.host + '/home/user/audit',
                  data: {
                    face: user.userInfo.avatarUrl,
                    nickname: user.userInfo.nickName,
                    sex: user.userInfo.gender
                  },
                  method: "POST",
                }, () => {
                  userInfo.face = user.userInfo.avatarUrl;
                  userInfo.nickname = user.userInfo.nickName;
                  userInfo.sex = user.userInfo.gender;
                  that.setData({
                    userInfo
                  })
                })
              }
            })
          }
        },
      })
    },
    /**
     * 网络请求封装
     * @param {*} req_data  
     * url 请求地址,
     * loadingTip:加载中提示，如果存在，先显示loading
     * @param {*} success_func 成功回调方法
     * @param {*} fail_func 失败回调方法,code 不为零时也会调用
     * @param {*} complete 最终执行的方法
     */
    request: function (req_data, success_func, fail_func = null, complete = null) {
      let that = this;
      let Authorization = wx.getStorageSync('Authorization');

      if (req_data.loadingTip) {
        wx.showLoading({
          title: req_data.loadingTip,
          mask: true
        })
      }
      req_data.header = {
        'content-type': 'application/json',
        'Accept': 'application/json, text/javascript, */*; q=0.01'
      };

      if (Authorization) {
        req_data.header.Authorization = Authorization;
      }
      req_data.success = function (res) { //成功处理
        if (res.statusCode == 200) {
          if (res.header.Authorization) {
            wx.setStorage({
              data: res.header.Authorization,
              key: 'Authorization',
            })
          }
          let data = res.data;
          if (data.code == 0) {
            success_func(data.result || data);
          } else {
            if (fail_func) {
              return fail_func(data);
            }
            wx.showModal({
              showCancel: false,
              content: data.result || data.msg + "" || data.message + "",
            })

          }
        } else if (res.statusCode == 401) {

          //进行登陆
          wx.showModal({
            content: '请先授权登陆',
            showCancel: true,
            title: '登陆提示',
            success: (result) => {
              if (result.confirm) {
                wx.login({
                  success: (loginRes) => {
                    // console.log("loginRes",loginRes);
                    //code 登陆
                    wx.request({
                      url: that.data.host + "/home/login?code=" + loginRes.code,
                      success: (res1) => {
                        let user = res1.data;
                        // console.log("res1",res1);
                        wx.showToast({
                          title: '登陆成功',
                        })
                        wx.setStorageSync('Authorization', user.data.access_token)
                        that.data.userInfo = getApp().globalData.userInfo = user.data;
                        console.log("that.userInfo.audit", that.data.userInfo);
                        if (!that.data.userInfo.audit) {
                          console.log("that.getUserProfile()");
                          that.getUserProfile();
                        }
                        that.login_reload()
                      },
                      fail: (e) => {
                        console.log(e);
                        wx.showToast({
                          title: e.errMsg || '网络异常',
                          icon: 'none'
                        })
                      },
                    })
                  },
                  fail: (e) => {
                    console.log("wx.login失败", e);
                    wx.showToast({
                      title: e.errMsg || '没有授权成功',
                      icon: 'none'
                    })
                  },
                })
              }
            },
          })
        } else {
          console.log("res.statusCode", res.statusCode);
          if (fail_func) {
            return fail_func(res);
          }
          wx.showModal({
            showCancel: false,
            content: res.data.message || res.data || "网络异常",
          })

        }
      };
      req_data.fail = function (e) { //失败处理
        fail_func ? fail_func(e) : wx.showModal({
          showCancel: false,
          content: '网络异常：' + e.errMsg
        });

      }
      req_data.complete = function (e) { //失败处理
        req_data.loadingTip ? wx.hideLoading() : '';
        complete ? complete(e) : '';
      }
      wx.request(req_data);
    },

  }
})